#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "inst.h"

#define DEV "/dev/hda"

int main(void)
{
	struct stage2 buf, bhw;
	int len, fd, n, i, log, cnt;
	unsigned long long blocks;
	struct stage1 st1;

	fd = open( "/boot/bhw2", O_RDONLY);
	len = read( fd, &bhw, 512);
	close(fd);

	blocks = cnt = 0;
	fd = open( DEV, O_RDONLY);
	while ( ( n = read( fd, &buf, 512) ) > 0 )
	{
		if (buf.magic == bhw.magic )  //check for magical numbers
		{
			log = 1;
			cnt++;
			for ( i = 0; i < len; i++ ) // compare whole block
			{
				if ( buf.nil[i] != bhw.nil[i] )
				{
					log = 0;
					break;
				}

			}

			if ( log ) // if file found
		   	{
				//printf ( "mam\n" );
				break;
			}

		}
		blocks++;

	}

	close(fd);

	if ( ! log ) 
	    exit(1);
	
	fd = open( "/boot/bhw", O_RDONLY);
	len = read( fd, &st1, 512);
	close(fd);
	
	printf ( "Second stage umieszczony w %llu sekotrze.\n", blocks );
	st1.dap_lba = blocks;

	fd = open( "/boot/bhw", O_WRONLY);
	len = write( fd, &st1, 512);
	close(fd);

	return 0;
}
